#include <iostream>

using std::cout;
using std::endl;

class Single {
private:
    Single() {
        cout << "Single()" << endl;
    }

    ~Single() {
        cout << "~Single()" << endl;
    }

public:
    static Single* getInstance() {
        if (_pInstance == nullptr) {
            _pInstance = new Single();
            // 创建时自动注册 AutoRelease
            static AutoRelease ar(_pInstance);
        }
        return _pInstance;
    }

    void print() {
        cout << "Single::print()" << endl;
    }

    // 禁止拷贝和赋值
    Single(const Single&) = delete;
    Single& operator=(const Single&) = delete;

private:
    static Single* _pInstance;

    class AutoRelease {
    public:
        AutoRelease(Single* p)
            : _pInstance(p) {
            cout << "AutoRelease(Single *)" << endl;
        }

        ~AutoRelease() {
            if (_pInstance) {
                delete _pInstance;
                _pInstance = nullptr;
            }
        }

    private:
        Single* _pInstance;
    };

    friend class AutoRelease;
};

Single* Single::_pInstance = nullptr;

void test() {
    Single* ps1 = Single::getInstance();
    Single* ps2 = Single::getInstance();
    ps1->print();
    ps2->print();
}

int main() {
    test();
    return 0;
}

